def railfence_encrypt(text, key):
    # 确保密钥是有效的整数
    try:
        key = int(key)
    except ValueError:
        return "密钥必须是整数"

    if key <= 1:
        return text

    # 创建轨道矩阵
    rails = [[] for _ in range(key)]
    rail_index = 0
    direction = 1  # 1 表示向下，-1 表示向上

    for char in text:
        rails[rail_index].append(char)

        # 改变方向
        if rail_index == 0:
            direction = 1
        elif rail_index == key - 1:
            direction = -1

        rail_index += direction

    # 组合所有轨道上的字符
    encrypted_text = ''.join([''.join(rail) for rail in rails])
    return encrypted_text


def railfence_decrypt(text, key):
    # 确保密钥是有效的整数
    try:
        key = int(key)
    except ValueError:
        return "密钥必须是整数"

    if key <= 1:
        return text

    # 创建轨道矩阵并计算每个轨道的长度
    length = len(text)
    rails = [[] for _ in range(key)]
    rail_lengths = [0] * key

    rail_index = 0
    direction = 1

    # 计算每个轨道的字符数量
    for i in range(length):
        rail_lengths[rail_index] += 1

        if rail_index == 0:
            direction = 1
        elif rail_index == key - 1:
            direction = -1

        rail_index += direction

    # 填充轨道矩阵
    index = 0
    for i in range(key):
        rails[i] = list(text[index:index + rail_lengths[i]])
        index += rail_lengths[i]

    # 重新排列字符
    decrypted_text = ""
    rail_index = 0
    direction = 1

    for _ in range(length):
        # 从当前轨道取出一个字符
        decrypted_text += rails[rail_index].pop(0)

        # 改变方向
        if rail_index == 0:
            direction = 1
        elif rail_index == key - 1:
            direction = -1

        rail_index += direction

    return decrypted_text